<?php
class NewsModel extends CommonModel {
	public function __construct(){
		parent::__construct();
	}
	//生成下拉框
	function make_option_data(){
		$list = M("Newstype")->where("status='1'")->order("id,disorder desc")->select();
		if($list){
			$list = tree_format($list,0,0,"├─");
		}
		return $list ;
	}
	//获取新闻类型列表数据
	public function queryNewsTypeList($p , $per_page = 100 ){
		if($p <=0 ){
			$p = 1 ;
		}
		import('Library.Page' , APP_PATH);
		$limit = ($p-1)*$per_page;
		$limit.=",{$per_page}";
		$where = '1= 1 ';
		$total = M("Newstype")->where($where)->count();
		$page = new Page($total,$per_page);
		$page_string =  $page->show();
		$list = M("Newstype")->where($where)->order("id,disorder desc")->select();
		
		$ids = '' ;
		if($list){
			foreach($list AS $k1 => $v1 ){
				$count = M("News")->where("typeid in ({$v1['id']})")->count();
				$num = "&nbsp;&nbsp;【<a href='javascript:void(0)' onclick='jump_news(\"{$v1['id']}\")'><font color='red'>".($count) ."</font></a>】";
				$list[$k1]['num'] = $num;
				$list[$k1]['status'] = ($v1['status'] == 1 )?"<font color='green'>开启</font>":"<font color='red'>关闭</font>";
				$pic_url = C("upload_domain")."/Newstype/{$v1['pic']}" ; 
				$list[$k1]['pic']  = ($v1['pic'] != '' )?"<img src='{$pic_url}' width='80' height='80'>":'无';
			}
			$list = tree_format($list,0,0,"├─├─");
		}
		return array('list'=>$list , 'page_string'=>$page_string);
	}
	//添加咨询类别
	public function insertNewType(){
		$d = M("Newstype");
		$_POST['info']['path'] = $this->getPath($_POST['pid']);
		if($row=$d->create($_POST['info'])){
				if($d->add()){
					write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "添加分类{$_POST['info']['typename']}成功" );
					return array('status'=>1 , 'message'=>'添加成功');
				}else{
					write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "添加分类{$_POST['info']['typename']}失败" );
					return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
				}
		}else{
			write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
			return array('status'=>0 , 'message'=>'数据创建失败');
		}
	}
	//查询path
	public function getPath($id){
		$info = M("Newstype")->where("id='{$id}'")->find();
		if(!$info){
			return 0 ; 
		}
		return $info['path']."-".$info['id'];
	}
	//修改咨询类别
	public function editNewsType(){
		$d = M("Newstype");
		$_POST['info']['path'] = $this->getPath($_POST['info']['pid']);
		if($row=$d->create($_POST['info'])){
			if($row['id']){
				$num = $d->save();
				if($num >= 1 ){
					//修改状态
					$map['path'] = array('like'=>"");
					$d->where("path like '%{$_POST['info']['path']}%'")->save(array('status'=>$_POST['info']['status']));
					write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "修改分类{$_POST['info']['typename']}成功" );
					return array('status'=>1 , 'message'=>'数据修改成功');
				}
				write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "修改分类{$_POST['info']['typename']}失败" );
				return array('status'=> 0  , 'message'=>'网络繁忙你可能没修改数据。');
			}else{
				write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "非法操作" );
				return array('status'=>0 , 'message'=>'非法操作');
			}
		}else{
			write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败失败" );
			return array('status'=>0 , 'message'=>'数据创建失败');
		}
	}
	//上传图片
	public function upload_pic(){
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 3145728 ;// 设置附件上传大小
			$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->savePath =  './Data/Upload/Newstype/';// 设置附件上传目录
			$upload->autoSub = true;//使用子目录保存上传文件
			$upload->subType = 'date';//使用日期模式创建子目录
			$upload->dateFormat = 'Ymd';//设置子目录日期格式
			if(!$upload->upload()) {// 上传错误提示错误信息
				return array('status' => 0 , 'message'=> $upload->getErrorMsg());
			}else{// 上传成功 获取上传文件信息
				$info =  $upload->getUploadFileInfo();
			}
			return array('status'=>1 , 'message'=>'success' , 'pic'=>$info[0]['savename'] ) ;
			
	}
	//上传新闻的缩略图图片
	public function upload_news_pic(){
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  './Data/Upload/News/';// 设置附件上传目录
		$upload->autoSub = true;//使用子目录保存上传文件
		$upload->subType = 'date';//使用日期模式创建子目录
		$upload->dateFormat = 'Ymd';//设置子目录日期格式
		if(!$upload->upload()) {// 上传错误提示错误信息
			return array('status' => 0 , 'message'=> $upload->getErrorMsg());
		}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
		}
		return array('status'=>1 , 'message'=>'success' , 'pic'=>$info[0]['savename'] ) ;
			
	}	
	//根据新闻的类别ID查询类别名称
	public function getTypeName($id){
		$info = M("Newstype")->where("id='{$id}'")->find();
		return $info['typename'];
	}
	//根据新闻的类别ID 返回数据
	public function getNewsTypeData($id){
		$info = M("Newstype")->where("id='{$id}'")->find();
		return $info;
	}
	//根据新闻咨询的Id获取数据
	public function getNewDataById($id){
		return M("News")->where("id={$id}")->find();
	}
	//获取新闻列表数据
	public function queryNewsList($p , $per_page = 100 , $where = array() ){
		if($p <=0 ){
			$p = 1 ;
		}
		$getwhere = " where 1 = 1 " ;
		if(isset($where['title']) &&  $where['title'] ){
			$getwhere.=" AND a.title like '%{$where['title']}%' ";
		}
		if(isset($where['flag']) &&  $where['flag'] ){
			$getwhere.=" AND a.flag like '%{$where['flag']}%' ";
		}
		if(isset($where['typeid']) &&  $where['typeid'] ){
			$getwhere.=" AND a.typeid = '{$where['typeid']}' ";
		}
		if( in_array($where['status'] , array('1', '0' ) ) ){
			$getwhere.=" AND a.status = '{$where['status']}' ";
		}
		//echo $getwhere ;
		import('Library.Page' , APP_PATH);
		$limit = ($p-1)*$per_page;
		$limit.=",{$per_page}";
		$where = '1= 1 ';
		$sql_count = "select count(*) as c from ".C("DB_PREFIX")."news as a left join ".C("DB_PREFIX")."newstype as b on a.typeid = b.id {$getwhere}" ;
		$count_data = M()->query($sql_count);
		$total = $count_data[0]['c'];

		$page = new Page($total,$per_page);
		$page_string =  $page->show();
		
		$sql = "select a.*  , b.typename   from ".C("DB_PREFIX")."news as a left join ".C("DB_PREFIX")."newstype as b on a.typeid = b.id {$getwhere} order by a.create_date desc , weight desc limit {$limit}" ;
		$list = M()->query($sql);
		
		if($list){
			foreach($list AS $k1 => $v1 ){
				if($v1['status'] == 1 ){
					$list[$k1]['status'] = "<input type='radio' name='status[{$k1}]' checked value='1' onclick='editStatus({$v1['id']} , 1 )'>开启<input type='radio' name='status[{$k1}]' value='0' onclick='editStatus({$v1['id']} , 0 )'>关闭";
				}else{
					$list[$k1]['status'] = "<span style='color:red'><input type='radio' name='status[{$k1}]' value='1' onclick='editStatus({$v1['id']} , 1 )' >开启<input type='radio' name='status[{$k1}]' checked value='0' onclick='editStatus({$v1['id']} , 0 )'>关闭</span>";

				}
				
				$list[$k1]['title'] = msubstr($v1['title'],0,20)."<font color='red'>". $this->getStrAttrNews($v1['flag'])."</font>";
				$list[$k1]['create_date'] = isset($v1['create_date'])?date("Y-m-d H:i",$v1['create_date']):'' ;
				$list[$k1]['modify_date'] = isset($v1['modify_date'])?date("Y-m-d H:i",$v1['modify_date']):'' ;
				if(file_exists("./Data/Upload/News/{$v1['image']}") && $v1['image'] != '' ){
					$pic_url = C("upload_domain")."/News/{$v1['image']}";;
					$list[$k1]['image'] = "<img src='{$pic_url}' width='80' height='80'>";
				}else{
					$list[$k1]['image'] = '图片没有' ;
				}
				if(file_exists("./Data/Upload/News/{$v1['pc_image']}") && $v1['pc_image'] != '' ){
					$pic_url = C("upload_domain")."/News/{$v1['pc_image']}";;
					$list[$k1]['pc_image'] = "<img src='{$pic_url}' width='80' height='80'>";
				}else{
					$list[$k1]['pc_image'] = '图片没有' ;
				}
				if(file_exists("./Data/Upload/News/{$v1['wap_image']}") && $v1['wap_image'] != '' ){
					$pic_url = C("upload_domain")."/News/{$v1['wap_image']}";;
					$list[$k1]['wap_image'] = "<img src='{$pic_url}' width='80' height='80'>";
				}else{
					$list[$k1]['wap_image'] = '图片没有' ;
				}
				
			}
			
		}
		return array('list'=>$list , 'page_string'=>$page_string);
	}
	//获取新闻资讯的属性
	public function getStrAttrNews($flag = '' ){
		$str = '' ;
		$res = C("content_att");
		$flag_data = explode("," , $flag );

		foreach($flag_data as $k => $v ){
			if(isset($res[$v]) && $res[$v]){
				$str.=$res[$v].",";
			}	
		}
		$str = rtrim($str , ',');
		return $str ;
	}
	//插入新闻
	function insertNews(){
		if($_POST['info']['title'] == '' ){
			return array('status'=>false  , 'message'=>'标题不可以为空' );
		}elseif($_POST['info']['content'] == '' ){
			return array('status'=>false  , 'message'=>'内容不可以为空' );
		}
		$_POST['info']['create_date'] = strtotime($_POST['info']['create_date']);
		$_POST['info']['modify_date'] = strtotime($_POST['info']['create_date']);
		$_POST['info']['addperson'] = $this->username;
		if(isset($_POST['flag'])){
			$_POST['info']['flag'] = implode(",",$_POST['flag']);
		}
		if($_POST['info']['content'] != '' && $_POST['info']['introduce'] == '' ){
			$_POST['info']['introduce'] = msubstr(cutstr_html($_POST['info']['content']), 0 , 100 , 'utf-8' , false );
		}
	
		$d = M("News");
		if($row=$d->create($_POST['info'])){
			if($d->add()){
				write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "添加新闻{$_POST['info']['title']}成功" );
				return array('status'=>1 , 'message'=>'添加成功');
			}else{
				write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "添加新闻{$_POST['info']['title']}失败" );
				return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
			}
		}else{
			write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
			return array('status'=>0 , 'message'=>'数据创建失败');
		}
	}
	//插入新闻
	function editNews(){
		if($_POST['info']['title'] == '' ){
			return array('status'=>false  , 'message'=>'标题不可以为空' );
		}elseif($_POST['info']['content'] == '' ){
			return array('status'=>false  , 'message'=>'内容不可以为空' );
		}
		$_POST['info']['create_date'] = strtotime($_POST['info']['create_date']);
		$_POST['info']['modify_date'] = time();
		if(isset($_POST['flag'])){
			$_POST['info']['flag'] = implode(",",$_POST['flag']);
		}
		if($_POST['info']['content'] != '' && $_POST['info']['introduce'] == '' ){
			$_POST['info']['introduce'] = msubstr(cutstr_html($_POST['info']['content']), 0 , 100 , 'utf-8' , false );
		}
	
		$d = M("News");
		if($row=$d->create($_POST['info'])){
			if($d->save()){
				write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "修改新闻{$_POST['info']['title']}成功" );
				return array('status'=>1 , 'message'=>'修改成功');
			}else{
				write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "修改新闻{$_POST['info']['title']}失败" );
				return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
			}
		}else{
			write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
			return array('status'=>0 , 'message'=>'数据创建失败');
		}
	}	
	//修改状态
	public function doStatus($data = array() ){
		$d = M("News");
		$num = $d->where("id = '{$data['id']}'")->save(array('status'=>$data['status'] , 'modify_date'=>time()));
		$sql = $d->getLastSql() ;
		if($num >=1 ){
			write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 1 , "修改新闻id:{$data['id']}状态成功" );
			return array('status'=>1 , 'message'=>'修改成功');
		}
		write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 0 , "修改新闻id:{$data['id']}状态失败" );
			return array('status'=>0 , 'message'=>'修改失败你可能没有修改数据');
	}
	//上传编辑器的图片
	public function upload_kindeditor(){
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  __ROOTPATH__.'/Data/Upload/K/';// 设置附件上传目录
		$upload->autoSub = true;//使用子目录保存上传文件
		$upload->subType = 'date';//使用日期模式创建子目录
		$upload->dateFormat = 'Ymd';//设置子目录日期格式
		if(!$upload->upload()) {// 上传错误提示错误信息
			return array('status' => 0 , 'message'=> $upload->getErrorMsg());
		}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
		}
		return array('status'=>1 , 'message'=>'success' , 'url'=>C("upload_domain")."/K/".$info[0]['savename'] ) ;
	}	
	//删除资讯
    public function del($data = array() ){
        $info = M("News")->where("id={$data['id']}")->find();
        if(!$info){
            return array('status'=> 0 ,'message'=>'参数错误') ;
        }
        $num = M("News")->where("id={$data['id']}")->delete(); 
        $sql = M("News")->getLastSql();
        if($num){
            write_action_log($sql, getModuleAction(),$this->username,get_client_ip(),1,"删除资讯--{$info['title']}--成功");
            return array('status'=> 1 ,'message'=>'操作成功') ;
        }else{
            write_action_log($sql, getModuleAction(),$this->username,get_client_ip(),0,"删除资讯--{$info['title']}--失败");
            return array('status'=> 0 ,'message'=>'网络繁忙请稍后') ;
        }
    }
}
